package com.ton.task.tron;
import com.ton.common.entity.TonPayOrder;
import com.ton.context.RedisContext;
import com.ton.common.service.PayOrderService;
import com.ton.utils.quartz.QueueUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 订单监听 - 传入一个账户account
 */
@Slf4j
@Component
@DisallowConcurrentExecution
public class OrderListener extends QuartzJobBean {

    @Autowired
    private RedisContext redisContext;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private PayOrderService payOrderService;

    @Autowired
    private QueueUtils queueUtils;

    /**
     * 定时任务触发时间
     * @param context 定时任务环境
     * @throws JobExecutionException 异常处理
     */
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String account = (String)jobDataMap.get("address"); //监听的地址
        String privateKey = (String)jobDataMap.get("privateKey"); //监听的私钥
        String jobName = (String)jobDataMap.get("jobName"); //任务名称
        Long orderId = (Long)jobDataMap.get("orderId"); //订单ID

        TonPayOrder tonPayOrder = null;

        //tronUtils.checkIfTronAddressTrue(account);

        //取数据 - 判断有没有过期
        String payKey = redisContext.getOrderPayKey(String.valueOf(orderId));
        Object o = redisTemplate.opsForValue().get(payKey);
        if(Objects.isNull(o)){
            log.info("订单失败!----->>@!");
            // 关闭定时任务
            stopTask(jobName); //关闭线程
            return;
        }

    }

    /**
     * 关闭定时任务
     */
    public void stopTask(String jobName){
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            System.out.println("删除定时任务出错："+e.getMessage());
        }
    }

    /**
     * 订单完成的调用 方法
     * @param tonPayOrder 订单对象
     * @param jobName 定时任务名称
     * @param coinType 收款类型
     * @param balanceTrx trx
     * @param balanceTrc20 trc
     */
    public void orderCompletion(TonPayOrder tonPayOrder, String jobName, Integer coinType, Long balanceTrx, Long balanceTrc20) {
        //返回数据
        log.info("完成订单!----->>" + tonPayOrder.getAmount());

        //更新订单表
        TonPayOrder tonPayOrderUpdate = payOrderService.getPayOrderById(tonPayOrder.getId());
        tonPayOrderUpdate.setStatus(1); //状态设为已完成
        payOrderService.updatePayOrder(tonPayOrderUpdate);

        //查询账户表
        //TronAccount tronAccount= tronAccountService.getTronAccount(payOrder.getAddress(),payOrder.getPrivateKey());
//        tronAccount.setIsOrderFlow(0); //设置没有走流程
//        tronAccount.setIsReuse(1); //设置可复用   说明：订单完成后账户设置为可复用方便后续订单处理
//        tronAccount.setBalanceTrc20(balanceTrc20);
//        tronAccount.setBalanceTrx(balanceTrx);
        //tronAccountService.updateById(tronAccount); //更新账户表

        //调用回调地址.....
        //String accountReuseKey = redisContext.getAccountReuse(tonPayOrder.getAddress());
        //redisTemplate.delete(accountReuseKey);//移除key

        //创建一个 redis缓存 用于收银台轮询查询使用
        String statusKey = redisContext.getOrderStatus(String.valueOf(tonPayOrder.getId()));

        //存1表示已交易已完成 0表示交易未完成
        redisTemplate.opsForValue().set(statusKey,1,1, TimeUnit.DAYS);

        //更新任务
        stopTask(jobName); //关闭线程
    }

}
